﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using BerkeleyDB;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace _4591BRD
{
    class MakeRankData
    {        
        private int workID = 0;
        private DateTime curDate;

        public MakeRankData(int id, DateTime currentDate)
        {
            workID = id;
            curDate = currentDate;
        }

        public void MakeDailyRank()
        {
            BTreeDatabaseConfig btreeDBConfig = new BTreeDatabaseConfig();
            btreeDBConfig.Creation = CreatePolicy.IF_NEEDED;
            btreeDBConfig.PageSize = 512;
            using (BTreeDatabase btreeDB = BTreeDatabase.Open(Common.WebDataPath + "bdb.db", btreeDBConfig))
            {
                List<CharDataObj> objlist = new List<CharDataObj>();

                for (int i = 0; i < 10; i++)
                {
                    CharDataObj theobj = new CharDataObj();
                    theobj.CharID = i;
                    theobj.AddDataValue("testdata1", 888 + i);
                    theobj.AddDataValue("testdata2", 999 + i);
                    objlist.Add(theobj);

                    
                }

                BinaryFormatter formatter = new BinaryFormatter();
                MemoryStream dataValue = new MemoryStream();

                formatter.Serialize(dataValue, objlist);


                //btreeDB.Put(new DatabaseEntry(BitConverter.GetBytes((int)1)), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("Hello World!")));
                //KeyValuePair<DatabaseEntry, DatabaseEntry> pair = btreeDB.Get(new DatabaseEntry(BitConverter.GetBytes((int)1)));



                btreeDB.Put(new DatabaseEntry(BitConverter.GetBytes((int)1)), new DatabaseEntry(dataValue.GetBuffer()));
                KeyValuePair<DatabaseEntry, DatabaseEntry> pair = btreeDB.Get(new DatabaseEntry(BitConverter.GetBytes((int)1)));

                MemoryStream dt = new MemoryStream();
                dt.Write(pair.Value.Data, 0, pair.Value.Data.Length);
                dt.Position = 0;
                List<CharDataObj> objData = (List<CharDataObj>)formatter.Deserialize(dt);

                for (int i = 0; i < objData.Count; i++)
                    System.Console.WriteLine(objData[i].CharID + "" + objData[i].ObjData["testdata1"]);
            }
            /*
            string dataFile;
            StreamWriter swData;
            int iCount = 0;

            string dateCreateStr = DateTime.Now.ToString("yyyy-MM-dd HH:MM:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
            string tblName = "";
            string sql = "";
            string dateTableStr = curDate.Year.ToString() + "_" + curDate.Month.ToString() + "_" + curDate.Day.ToString();
            string dateStr = curDate.ToString("yyyy-MM-dd", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            SqlDataReader reader;
            string strRankName;

            string path = Common.WebDataPath + "Daily\\" + dateStr + "\\RankData\\";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            try
            {
                //日功勋排名
                strRankName = "CharPointRankDaily";
                dataFile = path + strRankName + ".txt";
                swData = new StreamWriter(dataFile, false, Encoding.GetEncoding("GB2312"));

                swData.WriteLine("CreateTime " + dateCreateStr);

                tblName = "tbCharPointDaily_" + dateTableStr;
                sql = "IF EXISTS (SELECT 1 FROM Sysobjects WHERE Type = 'U' AND Name = '" + tblName + "') ";
                sql += " SELECT * FROM " + tblName + " WITH (NOLOCK) ORDER BY PointTotal DESC";
                reader = SqlHelper.ExecuteReader(Common.ConnStrBRD, CommandType.Text, sql, null);
                iCount = 0;
                Log.WriteLine(1, "Start Make " + strRankName);
                while (reader.Read())
                {
                    iCount++;
                    int charid = int.Parse(reader["CharID"].ToString());
                    CurrentDateManager.Instance.GetCharData(charid, 0).SetRankValue(strRankName, iCount);
                    swData.WriteLine(strRankName + " " + iCount.ToString() + " " + charid.ToString() + " " + NameCacheManager.Instance.GetCharNameByID(charid) + " " + NameCacheManager.Instance.GetCountryByCharID(charid).ToString() + " " + NameCacheManager.Instance.GetTeamShortNameByCharID(charid) + " " + reader["PointTotal"].ToString());
                }
                reader.Close();
                swData.Close();
                Log.WriteLine(1, "Finish Make " + strRankName + ", Count = " + iCount.ToString());

                //日击杀排名
                strRankName = "CharKillRankDaily";
                dataFile = path + strRankName + ".txt";
                swData = new StreamWriter(dataFile, false, Encoding.GetEncoding("GB2312"));

                swData.WriteLine("CreateTime " + dateCreateStr);

                tblName = "tbCharKillDaily_" + dateTableStr;
                sql = "IF EXISTS (SELECT 1 FROM Sysobjects WHERE Type = 'U' AND Name = '" + tblName + "') ";
                sql += " SELECT * FROM " + tblName + " WITH (NOLOCK) ORDER BY KillTotal DESC";
                reader = SqlHelper.ExecuteReader(Common.ConnStrBRD, CommandType.Text, sql, null);
                iCount = 0;
                Log.WriteLine(1, "Start Make " + strRankName);
                while (reader.Read())
                {
                    iCount++;
                    int charid = int.Parse(reader["CharID"].ToString());
                    CurrentDateManager.Instance.GetCharData(charid, 0).SetRankValue(strRankName, iCount);
                    swData.WriteLine(strRankName + " " + iCount.ToString() + " " + charid.ToString() + " " + NameCacheManager.Instance.GetCharNameByID(charid) + " " + NameCacheManager.Instance.GetCountryByCharID(charid).ToString() + " " + NameCacheManager.Instance.GetTeamShortNameByCharID(charid) + " " + reader["KillTotal"].ToString());
                }
                reader.Close();
                swData.Close();
                Log.WriteLine(1, "Finish Make " + strRankName + ", Count = " + iCount.ToString());

                //日军团排名
                DataTable tmpTB;
                DataTable tbData = new DataTable();
                tbData.Columns.Add("TeamID", typeof(int));
                tbData.Columns.Add("PointTotal", typeof(int));
                foreach (KeyValuePair<int, GameObject> obj in CurrentDateManager.Instance.TeamDataCacheDaily)
                {
                    tbData.Rows.Add(obj.Key, obj.Value.GetTeamValue("PointTotal"));
                }
                tbData.DefaultView.Sort = "PointTotal desc";
                tmpTB = tbData.DefaultView.ToTable().Copy();
                
                strRankName = "TeamRankDaily";
                dataFile = path + strRankName + ".txt";
                swData = new StreamWriter(dataFile, false, Encoding.GetEncoding("GB2312"));

                swData.WriteLine("CreateTime " + dateCreateStr);

                iCount = 0;
                Log.WriteLine(1, "Start Make " + strRankName);
                for (int i = 0; i < tmpTB.Rows.Count; i++)
                {
                    iCount++;
                    DataRow row = tmpTB.Rows[i];
                    int objID = int.Parse(row["TeamID"].ToString());
                    int objValue = int.Parse(row["PointTotal"].ToString());
                    NameCache theObj = NameCacheManager.Instance.GetTeamByID(objID);
                    swData.WriteLine(strRankName + " " + iCount.ToString() + " " + objID.ToString() + " " + theObj.TeamName + " " + theObj.CountryID + " " + theObj.ShortName + " " + objValue.ToString());
                }
                tbData.Clear();
                swData.Close();
                Log.WriteLine(1, "Finish Make " + strRankName + ", Count = " + iCount.ToString());
            }
            catch (SqlException se)
            {
                Log.WriteError(se.Message);
            }
            catch (Exception e)
            {
                Log.WriteError(e.Message);
            }
             */
        }

        public void MakeMonthlyRank()
        {
            string dataFile;
            StreamWriter swData;
            int iCount = 0;

            string dateCreateStr = curDate.ToString("yyyy-MM-dd HH:MM:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
            string tblName = "";
            string sql = "";
            string monTableStr = curDate.Year.ToString() + "_" + curDate.Month.ToString();
            string monStr = curDate.ToString("yyyy-MM", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            SqlDataReader reader;
            string strRankName;

            string path = Common.WebDataPath + "Monthly\\" + monStr + "\\RankData\\";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            try
            {
                //月功勋排名
                strRankName = "CharPointRankMonthly";
                dataFile = path + strRankName + ".txt";
                swData = new StreamWriter(dataFile, false, Encoding.GetEncoding("GB2312"));

                swData.WriteLine("CreateTime " + dateCreateStr);

                tblName = "tbCharPointMonthly_" + monTableStr;
                sql = "IF EXISTS (SELECT 1 FROM Sysobjects WHERE Type = 'U' AND Name = '" + tblName + "') ";
                sql += " SELECT * FROM " + tblName + " WITH (NOLOCK) ORDER BY PointTotal DESC";
                reader = SqlHelper.ExecuteReader(Common.ConnStrBRD, CommandType.Text, sql, null);
                iCount = 0;
                Log.WriteLine(1, "Start Make " + strRankName);
                while (reader.Read())
                {
                    iCount++;
                    int charid = int.Parse(reader["CharID"].ToString());
                    CurrentDateManager.Instance.GetCharData(charid, 1).SetRankValue(strRankName, iCount);
                    swData.WriteLine(strRankName + " " + iCount.ToString() + " " + charid.ToString() + " " + NameCacheManager.Instance.GetCharNameByID(charid) + " " + NameCacheManager.Instance.GetCountryByCharID(charid).ToString() + " " + NameCacheManager.Instance.GetTeamShortNameByCharID(charid) + " " + reader["PointTotal"].ToString());
                }
                swData.Close();
                reader.Close();
                Log.WriteLine(1, "Finish Make " + strRankName + ", Count = " + iCount.ToString());


                //月击杀排名
                strRankName = "CharKillRankMonthly";
                dataFile = path + strRankName + ".txt";
                swData = new StreamWriter(dataFile, false, Encoding.GetEncoding("GB2312"));

                swData.WriteLine("CreateTime " + dateCreateStr);

                tblName = "tbCharKillMonthly_" + monTableStr;
                sql = "IF EXISTS (SELECT 1 FROM Sysobjects WHERE Type = 'U' AND Name = '" + tblName + "') ";
                sql += " SELECT * FROM " + tblName + " WITH (NOLOCK) ORDER BY KillTotal DESC";
                reader = SqlHelper.ExecuteReader(Common.ConnStrBRD, CommandType.Text, sql, null);
                iCount = 0;
                Log.WriteLine(1, "Start Make " + strRankName);
                while (reader.Read())
                {
                    iCount++;
                    int charid = int.Parse(reader["CharID"].ToString());
                    CurrentDateManager.Instance.GetCharData(charid, 1).SetRankValue(strRankName, iCount);
                    swData.WriteLine(strRankName + " " + iCount.ToString() + " " + charid.ToString() + " " + NameCacheManager.Instance.GetCharNameByID(charid) + " " + NameCacheManager.Instance.GetCountryByCharID(charid).ToString() + " " + NameCacheManager.Instance.GetTeamShortNameByCharID(charid) + " " + reader["KillTotal"].ToString());
                }
                swData.Close();
                reader.Close();
                Log.WriteLine(1, "Finish Make " + strRankName + ", Count = " + iCount.ToString());
                
                //月军团排名
                for (int i = 2; i <= 16; i *= 2)
                {
                    DataTable tmpTB;
                    DataTable tbData = new DataTable();
                    tbData.Columns.Add("TeamID", typeof(int));
                    tbData.Columns.Add("PointTotal", typeof(int));
                    foreach (KeyValuePair<int, GameObject> obj in CurrentDateManager.Instance.TeamDataCacheMonthly)
                    {
                        NameCache theObj = NameCacheManager.Instance.GetTeamByID(obj.Key);

                        if (theObj.CountryID == i || i == 16)
                            tbData.Rows.Add(obj.Key, obj.Value.GetTeamValue("PointTotal"));
                    }
                    tbData.DefaultView.Sort = "PointTotal desc";
                    tmpTB = tbData.DefaultView.ToTable().Copy();

                    strRankName = "TeamRankMonthly_" + i.ToString();
                    dataFile = path + strRankName + ".txt";
                    swData = new StreamWriter(dataFile, false, Encoding.GetEncoding("GB2312"));

                    swData.WriteLine("CreateTime " + dateCreateStr);

                    iCount = 0;
                    Log.WriteLine(1, "Start Make " + strRankName + " Country = " + i.ToString());
                    for (int j = 0; j < tmpTB.Rows.Count; j++)
                    {
                        iCount++;
                        DataRow row = tmpTB.Rows[j];
                        int objID = int.Parse(row["TeamID"].ToString());
                        int objValue = int.Parse(row["PointTotal"].ToString());
                        NameCache theObj = NameCacheManager.Instance.GetTeamByID(objID);
                        swData.WriteLine(strRankName + " " + iCount.ToString() + " " + objID.ToString() + " " + theObj.TeamName + " " + theObj.CountryID + " " + theObj.ShortName + " " + objValue.ToString());
                    }
                    tbData.Clear();
                    swData.Close();
                    Log.WriteLine(1, "Finish Make " + strRankName + " Country = " + i.ToString() + ", Count = " + iCount.ToString());
                }
            }
            catch (SqlException se)
            {
                Log.WriteError(se.Message);
            }
            catch (IOException e)
            {
                Log.WriteError(e.Message);
            }
            catch (Exception e)
            {
                Log.WriteError(e.Message);
            }
        }
    }
}
